package com.fbms.module.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fbms.common.constants.Constants;
import com.fbms.common.exception.ServiceException;
import com.fbms.common.result.Res;
import com.fbms.common.result.ResBuilder;
import com.fbms.common.utils.StreamKit;
import com.fbms.module.system.bean.dto.SysMenuDTO;
import com.fbms.module.system.bean.dto.SysRoleDTO;
import com.fbms.module.system.bean.entity.SysRole;
import com.fbms.module.system.service.ISysRoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 类描述：TODO
 *
 * @ClassName SysRoleController
 * @Author HappyBoy
 * @Date 2023-03-21 16:33
 **/
@RestController
@RequestMapping("/role")
@Slf4j
@RequiredArgsConstructor
public class SysRoleController {

    private final ISysRoleService roleService;

    /**
     * 查询角色列表
     * @param role 角色信息
     * @param offset 页数
     * @param size 条数
     * @return 角色和菜单信息
     */
    @GetMapping("/list")
    public Res<IPage<SysRoleDTO>> getRoleList(@RequestParam(value = "roleInfo", required = false) SysRole role,
                                  @RequestParam(name = "offset", defaultValue = "0")Integer offset,
                                  @RequestParam(name = "size", defaultValue = "10")Integer size){
        IPage<SysRole> page = new Page<>(offset, size);
        return ResBuilder.of(roleService.getRolePageList(role, page));
    }

    /**
     * 保存角色信息
     * @param roleInfo 角色信息
     * @return 条数
     */
    @PostMapping("")
    public Res<Boolean> saveRole(@RequestBody SysRoleDTO roleInfo){
        // 校验角色名称是否重复
        String roleName = roleInfo.getName();
        if (Constants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(roleName))) {
            throw new ServiceException("角色名称已存在");
        }
        List<SysMenuDTO> menus = roleInfo.getMenuList();
        Boolean num = roleService.saveRole(roleInfo, StreamKit.mapToList(menus, SysMenuDTO::getId));
        return ResBuilder.of(num);
    }

    /**
     * 更新角色信息
     * @param roleId 角色Id
     * @param roleInfo 角色信息（包含菜单）
     * @return 条数
     */
    @PatchMapping("/{roleId}")
    public Res<Boolean> updateRole(@PathVariable String roleId, @RequestBody SysRoleDTO roleInfo){
        Boolean num = roleService.updateRole(roleId, roleInfo);
        return ResBuilder.of(num);
    }

}
